import ThemeBtn from '@/components/antd-comp/theme-btn'
// import SkillChatSheet from '@/components/bs-comp/sheets/SkillChatSheet'
import { useChatStore } from '@/components/Chat/chatStore'
import ListEmptyNone from '@/components/antd-comp/empty/emptyNone'
import { showMessage } from '@/components/antd-comp/message'
import { userContext } from '@/contexts/userContext'
import { useFuncsStore } from '@/store/funcStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Modal, Tooltip, message } from 'antd'
import moment from 'moment'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocation, useNavigate } from 'react-router-dom'
import { HisChatList, chatsDetail, deleteHisChatsApi, getChatsApi, getHisChatsApi } from '../../controllers/API'
import { useDebounce } from '../../util/hook'
import { generateUUID } from '../../utils'
import ChatPanne from './components/ChatPanne'
import {
  ChatAppAiIcon,
  ChatAppHisIcon,
  ChatAppMore,
  ChatAppOff,
  ChatAppSvgIcon1,
  ChatAppSvgIcon2,
  ChatAppSvgIcon3,
  ChatAppUnpack
} from './components/chatAppPageSvgInfo'
import './css/index.less'

export default function SkillChatPage() {
  const { t } = useTranslation()
  const { confirm } = Modal
  const { user } = useContext(userContext)
  const location = useLocation()
  const { state } = location
  const navigate = useNavigate()
  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = ['会话']
  useRouteStoreHook(routeNames)
  const { loadHistoryMsg, updateLimitInfo } = useChatStore()
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()

  const [selectChat, setSelelctChat] = useState<any>({
    id: '',
    chatId: '',
    type: '',
    /* 无权限信息 私密 下线  */
    disabled: false,
    tips: '',
    // 提示信息
    guideQuestion: [],
    // name
    name: '',
    logo: '',
    user_name: ''
  })

  // uuid
  function generateUUIDv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = crypto.getRandomValues(new Uint8Array(1))[0] % 16 | 0
      const v = c === 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    })
  }
  /* 日期 时间显示 */
  const formatCreateTime = createTime => {
    const createTimeMoment = moment(createTime)
    if (moment().isSame(createTimeMoment, 'day')) {
      // 显示时间
      return createTimeMoment.format('HH:mm')
    } else {
      // 显示日期 YYYY-MM-DD HH:mm:ss
      return createTimeMoment.format('MM/DD')
    }
  }

  // 对话列表
  const [chatList, setchatList] = useState([])
  const [chatId, setChatId] = useState('')
  const chatsRef = useRef(null)
  const [page, setpage] = useState(1)
  const [total, setTotal] = useState(0)
  /* 智能体列表 */
  const getChatsApiFun = num => {
    getChatsApi(num).then((res: any) => {
      if (res?.list) {
        setTotal(res.count)
        const list = [...chatList, ...res.list]
        setchatList(list)
      }
    })
  }
  /* 历史会话列表 */
  const getHisChatsApiFun = (num, type = '') => {
    getHisChatsApi(num).then((res: any) => {
      if (res.list && res.list.length > 0) {
        setHisTotal(res.count)
        const list = type === 'none' ? [...res.list] : [...defHisData, ...res.list]
        setHisData(list)
      }else{
        message.warning('没有更多历史记录了');
      }
    })
  }

  /* citions判断 */
  const processCitations = citations => {
    if (!Array.isArray(citations) || citations.length === 0) {
      return { hasNonInternet: false, hasInternet: false }
    }
    const hasNonInternet = citations.some(c => c.type !== 'internet')
    const hasInternet = citations.some(c => c.type === 'internet')
    return { hasNonInternet, hasInternet }
  }

  // select flow(新建会话)
  const handlerSelectFlow = async card => {
    if (selectChat.disabled) {
      showMessage({
        content: selectChat.tips,
        type: 'warning'
      })
      return
    }
    // 会话ID
    const _chatId = generateUUID(32)
    // setSelelctChat({})
    setSelelctChat({
      name: card.name,
      id: card.id,
      // id: _chatId,
      chatId: _chatId,
      type: card.type,
      conversation_id: generateUUIDv4(),
      model_name: card.model_name,
      logo: card.logo,
      user_name: card.user_name,
      guide_word: card.guide_word,
      create_time: card.create_time,
      remember_mode: card.remember_mode,
      remember_last_num: card.remember_last_num,
      remember_last_minute: card.remember_last_minute,
      guide_question: card.guide_question
    })
    setChatId(_chatId)
    // 短期记忆模式 0 取最后N条， 1 取最后分钟数；  如果取最终分钟数， 条数有个上限，貌似是10
    updateLimitInfo({
      remember_mode: card.remember_mode,
      remember_last_num: card.remember_last_num,
      remember_last_minute: card.remember_last_minute
    })
    setTimeout(() => {
      chatsRef.current.scrollTop = 1
      fetchAndLoadHistory('', card.guide_word, card.create_time, '')
    }, 300)
  }

  // 加载历史消息
  async function fetchAndLoadHistory(
    conversation_id: string,
    guide_word: string,
    create_time: any,
    messageChatId: string
  ) {
    try {
      let history = {} as any
      let messages = []
      /* 没有conversation_id 直接走开场白 */
      if (conversation_id) {
        const res = (await HisChatList(conversation_id)) as any
        if (res?.list?.length > 0) {
          /* user 自己 assistant 机器人 */
          messages = res.list.flatMap(item => [
            {
              role: 'user',
              create_time: Math.floor(new Date(item.create_time).getTime() / 1000),
              content: [
                { text: item.query, type: 'text' },
                // item.query_image_url ? { image_url: { url: item.query_image_url }, type: 'image_url' } : {}
                item.query_image_url
                  ? {
                      image_url: { url: item.query_image.url, name: item.query_image.name },
                      type: 'image_url'
                    }
                  :  item.query_file_url
                  ? {
                      file_url: { url: item.query_file.url, name: item.query_file.name },
                      type: 'file_url'
                    }: {}
              ]
            },
            {
              role: 'assistant',
              create_time: item.create_time,
              // item.status === 0正常1暂停 && !item.answer 暂停并且没有值
              content: [
                {
                  text: item.status === 1 && !item.answer ? '回答已暂停' : item.answer,
                  type: 'text',
                  citations:
                    item.status === 1 && !item.answer
                      ? null
                      : processCitations(item?.citations).hasNonInternet
                      ? item.citations
                      : null,
                  internetCitations: processCitations(item?.citations).hasInternet ? item.citations : [],
                  // 显示暂停tag
                  chatStopTag: item.status === 1 ? 'stop' : ''
                }
              ]
            }
          ])
        }
      }

      /* 判断没有历史记录 显示开场白 */
      if (guide_word) {
        messages.unshift({
          role: 'assistant',
          create_time: Math.floor(new Date(create_time).getTime() / 1000),
          content: [{ text: guide_word, type: 'text' }]
        })
      }
      history = { messages }
      // await loadHistoryMsg(history, messageChatId)
      await loadHistoryMsg(history, '')
    } catch (error) {
      console.error('Failed to fetch and load history:', error)
    }
  }

  // 智能体点击出现 chat
  const handleSelectChat = useDebounce(
    async (e: any) => {
      const chat = e.chat
      if ((e.type && chat.assistant_id === chatId) || (!e.type && chat.id === chatId)) return

      let conversation_id = chat.conversation_id
      if (!conversation_id) {
        conversation_id = generateUUIDv4()
      }
      /* 数据 */
      setSelelctChat({
        id: chat.assistant_id,
        chatId: chat.assistant_id,
        type: 'assistant',
        conversation_id: e.type ? generateUUIDv4() : chat.conversation_id || conversation_id,
        /* 模型 */
        model_name: chat.model_name,
        /* 权限提示 */
        disabled:
          chat.assistatnt_status === 0 ||
          (!user.role.includes('admin') && chat.visable_status === 1 && !chat.is_app_ower),
        tips: `该智能体已${chat.assistatnt_status === 0 ? '下线' : '私密'} ，无法访问，请联系作者${
          chat.user_name
        }或超级管理员`,
        // name
        name: chat.name,
        logo: chat.logo,
        user_name: chat.user_name,
        guide_word: chat.guide_word,
        create_time: chat.create_time,
        remember_mode: chat.remember_mode,
        remember_last_num: chat.remember_last_num,
        remember_last_minute: chat.remember_last_minute,
        guide_question: chat.guide_question
      })
      setChatId(e.type ? chat.assistant_id : chat.id)
      // 短期记忆模式 0 取最后N条， 1 取最后分钟数；  如果取最终分钟数， 条数有个上限，貌似是10
      updateLimitInfo({
        remember_mode: chat.remember_mode,
        remember_last_num: chat.remember_last_num,
        remember_last_minute: chat.remember_last_minute
      })
      /* 历史信息 */
      setTimeout(() => {
        const messageChatId = e.type ? chat.id : chat.assistant_id // 取反id
        fetchAndLoadHistory(e.type ? '' : chat.conversation_id, chat.guide_word, chat.create_time, messageChatId)
      }, 300)
    },
    100,
    false
  )

  /* 
  默认数据
  */
  const [chatListHid, setChatListHid] = useState(true)
  /* 历史回话 */
  const [hispage, setHispage] = useState(1)
  const [histotal, setHisTotal] = useState(0)
  const [hisHid, sethisHid] = useState(false)
  const [defHisData, setHisData] = useState([])

  /* 点击展开更多 */
  const sliceLength = (type = '') => {
    if (type === 'his') {
      const num = hispage + 1
      setHispage(num)
      getHisChatsApiFun(num)
      return
    }
    const num = page + 1
    setpage(num)
    getChatsApiFun(num)
  }
  /* 删除 */
  const handleDelete = e => {
    confirm({
      title: t('prompt'),
      icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
      content: '确认删除该会话?',
      okText: t('delete'),
      okType: 'danger',
      cancelText: t('cancel'),
      autoFocusButton: null,
      centered: true,
      destroyOnClose: true,
      onOk() {
        deleteHisChatsApi(e.conversation_id).then(res => {
          showMessage({
            content: '删除成功',
            type: 'success'
          })
          setHisData(prevData => prevData.filter(item => item.conversation_id !== e.conversation_id))
          setHisTotal(histotal - 1)
        })
      }
    })
  }
  /* 显示链接 */
  const getDisplayName = (query, queryImageName) => {
    /* 有文字显示 */
    if (query) {
      return query
    }
    /* 判断单图片 */
    if (typeof queryImageName === 'string' && queryImageName.length > 12) {
      return `${queryImageName.slice(0, 4)}...${queryImageName.slice(-5)}`
    }
    return queryImageName || ''
  }
  /* 智能体列表 */
  useEffect(() => {
    getChatsApiFun(page)
  }, [])
  /* 跳转指定assistant_id */
  useEffect(() => {
    if (!state || !state.assistant_id) return
    const fetchAndHandleChat = async () => {
      try {
        const res = await chatsDetail(state.assistant_id)
        handleSelectChat({ chat: res, type: 'agent' })
      } catch (error) {
        console.error(error)
      } finally {
        navigate('.', { replace: true, state: undefined })
      }
    }
    fetchAndHandleChat()
  }, [state])

  // todo 修改对应code
  // if (!hasFuncPermission([Func.assistant.query], false)) {
  //   return <NoPermissionTem />
  // }
  return (
    <div className="relative flex h-full">
      {/* route title */}
      <span className="routeNames_title flexRowStart">
        {selectChat.logo && <img src={selectChat.logo} className="mr-[4px] h-[20px] w-[20px]" alt="" />}
        {selectChat.name || '会话'}
      </span>
      {/* 开启新对话 */}
      {chatId && (
        <ThemeBtn
          className="flexRowStart themeBtn_chatAppPage_create h-[30px] w-[120px]"
          onClick={e => {
            handlerSelectFlow(selectChat)
          }}
        >
          <svg
            className="mr-[0]"
            width="12"
            height="12"
            viewBox="0 0 12 12"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M2 6H10" stroke="white" strokeWidth="1.5" strokeLinecap="round" />
            <path d="M6 10L6 2" stroke="white" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
          开启新对话
        </ThemeBtn>
      )}
      {/* 智能体 */}
      <div className="relative mt-[-48px] h-[100%] w-[268px]">
        <div className="chatAppPage_conversation_head border-r-[1px] border-[#F5F7FB]">会话列表</div>
        <div
          ref={chatsRef}
          className="scroll no-scrollbar chatAppPageLeftCase h-full overflow-y-scroll border-r-[1px] border-[#F5F7FB]"
        >
          {/* 会话列表 */}
          <div className="flexCol">
            {/* 头部 */}
            <div
              className="flexRowStart answer_scrollCase flexRowJustBet cursonCase unselectable"
              onClick={() => {
                setChatListHid(!chatListHid)
              }}
            >
              <div className="flexRowStart answer_scroll_left">
                <ChatAppAiIcon></ChatAppAiIcon>
                <span className="answer_scrollName">智能体</span>
              </div>
              {chatListHid ? <ChatAppUnpack></ChatAppUnpack> : <ChatAppOff></ChatAppOff>}
            </div>
            {/* data */}
            {chatListHid &&
              chatList.length > 0 &&
              chatList.map((item, index) => {
                return (
                  <div
                    key={item.assistant_id + generateUUIDv4()}
                    onClick={() => handleSelectChat({ chat: item, type: 'agent' })}
                    className="flexRowStart answer_scrollCase answer_scrollCase_hover cursonCase"
                  >
                    {item.logo ? (
                      <img src={item.logo} className="h-[20px] w-[20px]" alt="" />
                    ) : index % 3 === 1 ? (
                      <ChatAppSvgIcon1 />
                    ) : index % 3 === 2 ? (
                      <ChatAppSvgIcon2 />
                    ) : (
                      <ChatAppSvgIcon3 />
                    )}
                    <span className="answer_scrollName answer_scrollName_cont domOverflowEllip">{item.name}</span>
                    {/* {item.flow_type ? <span className="answer_scroll_tag">{item.flow_type}</span> : null} */}
                  </div>
                )
              })}
            {/* 展开更多 */}
            {chatListHid && !chatList.length && <ListEmptyNone />}
            {chatListHid && chatList.length > 0 && chatList.length < total && (
              <div
                className="flexRowStart answer_scrollCase cursonCase"
                style={{ height: '36px' }}
                onClick={() => {
                  sliceLength()
                }}
              >
                <span className="answer_scrollMore">展开更多</span>
                <ChatAppMore></ChatAppMore>
              </div>
            )}
          </div>
          {/* 历史回话 */}
          <div className="histor_case flexCol">
            {/* 头部 */}
            <div
              className="flexRowStart unselectable answer_scrollCase flexRowJustBet cursonCase"
              onClick={() => {
                /* 点击显示重置数据 */
                if (!hisHid) {
                  const num = 1
                  setHispage(num)
                  getHisChatsApiFun(num, 'none')
                }
                sethisHid(!hisHid)
              }}
            >
              <div className="flexRowStart answer_scroll_left">
                <ChatAppHisIcon></ChatAppHisIcon>
                <span className="answer_scrollName">历史会话</span>
              </div>
              {hisHid ? <ChatAppUnpack></ChatAppUnpack> : <ChatAppOff></ChatAppOff>}
            </div>
            {/* data */}
            {hisHid && !defHisData.length && <ListEmptyNone />}
            {hisHid &&
              defHisData.length > 0 &&
              defHisData.map((item, index) => {
                return (
                  <div
                    key={item.id + generateUUIDv4()}
                    onClick={() => {
                      handleSelectChat({ chat: item, type: '' })
                    }}
                    className="flexCol history_scrollCase cursonCase"
                  >
                    <div className="flexRowStart">
                      {item.logo ? (
                        <img src={item.logo} className="mr-[4px] h-[20px] w-[20px]" alt="" />
                      ) : index % 3 === 1 ? (
                        <ChatAppSvgIcon1 />
                      ) : index % 3 === 2 ? (
                        <ChatAppSvgIcon2 />
                      ) : (
                        <ChatAppSvgIcon3 />
                      )}
                      <span className="history_scrollCase_name domOverflowEllip">
                        {getDisplayName(item.query, item.query_image?.name)}
                      </span>
                      {/* {item.typeName ? <span className="answer_scroll_tag">{item.typeName}</span> : null} */}
                    </div>
                    <div className="flexRowStart flexRowJustBet history_scrollCase_cont">
                      <span className="history_scrollCase_contWid domOverflowEllip">{item.answer}</span>
                      <span className="history_scrollCase_time domOverflowEllip">
                        {formatCreateTime(item.create_time)}
                      </span>
                    </div>
                    <div className="history_scrollCase_delIcon">
                      <Tooltip title={t('delete')}>
                        <svg
                          onClick={e => {
                            e.stopPropagation()
                            handleDelete(item)
                          }}
                          className="cursonCase"
                          width="28"
                          height="28"
                          viewBox="0 0 28 28"
                          fill="none"
                          xmlns="http://www.w3.org/2000/svg"
                        >
                          <path
                            d="M18.6668 8.66667H16.3335L15.6668 8H12.3335L11.6668 8.66667H9.3335V10H18.6668M10.0002 18.6667C10.0002 19.0203 10.1406 19.3594 10.3907 19.6095C10.6407 19.8595 10.9799 20 11.3335 20H16.6668C17.0205 20 17.3596 19.8595 17.6096 19.6095C17.8597 19.3594 18.0002 19.0203 18.0002 18.6667V10.6667H10.0002V18.6667Z"
                            fill="#7587A5"
                          />
                        </svg>
                      </Tooltip>
                    </div>
                  </div>
                )
              })}
            {hisHid && defHisData.length > 0 && defHisData.length < histotal && (
              <div
                className="flexRowStart answer_scrollCase cursonCase"
                style={{ height: '36px' }}
                onClick={() => {
                  sliceLength('his')
                }}
              >
                <span className="answer_scrollMore">展开更多</span>
                <ChatAppMore></ChatAppMore>
              </div>
            )}
          </div>
        </div>
      </div>
      {/* chat */}
      <ChatPanne data={selectChat} conversation={'会话'} useName={user.user_name}></ChatPanne>
    </div>
  )
}
